package com.nari.interplatform.utils;

import com.alibaba.fastjson.JSONObject;
import com.nari.common.core.constant.Constants;
import com.nari.interplatform.domain.*;
import com.nari.interplatform.mq.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MsgUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(MsgUtil.class);
    /**
     * 处理请求信息
     * @param msg
     * @return
     * @throws Exception
     */
    public static SwReq dealMsg(String msg,String encryptUsed,String compressUsed) throws Exception {
        JSONObject msgJson = new JSONObject();
        msgJson = JSONObject.parseObject(msg).getJSONObject("Request");
        String tranId = msgJson.get("tran_id") == null ? "" : msgJson.getString("tran_id");// 调用服务的交易编码
        String tranSeq = msgJson.get("tran_seq") == null ? "" : msgJson.getString("tran_seq");// 交易流水号
        String tranDate = msgJson.get("tran_date_req") == null ? "" : msgJson.getString("tran_date_req");// 交易发生日期，格式yyyyMMdd
        String tranTime = msgJson.get("tran_time_req") == null ? "" : msgJson.getString("tran_time_req");// 交易发生时间，格式HH24MISSFFF
        String body = msgJson.get("body") == null ? "" : msgJson.getString("body");// 业务报文
        SwReq SwReq = new SwReq();
        SwReqHeader head = new SwReqHeader();
        head.setTranId(tranId);
        head.setChannelId("SDSW.NFWB.SDGWDL");
        head.setChannelPsw("BE2F8D57918E8476E0532A640C4CB73B");
        head.setTranSeq(tranSeq);
        head.setTranDate(tranDate);
        head.setTranTime(tranTime);
        Compress compress = new Compress();
        compress.setUsed(compressUsed);
        Encrypt encrypt = new Encrypt();
        encrypt.setUsed(encryptUsed);
        Encode encode = new Encode();
        SwReqContentControl swReqContentControl = new SwReqContentControl();
        swReqContentControl.setCompress(compress);
        swReqContentControl.setEncrypt(encrypt);
        swReqContentControl.setEncode(encode);
        head.setSwReqContentControl(swReqContentControl);
        com.nari.interplatform.domain.SwReq swReq = new SwReq();
        swReq.setSwReqHeader(head);
        if(Constants.USED.equals(compress.getUsed())){
            //压缩
            body = GZIPUtils.compress(body);
        }
        if(Constants.USED.equals(encode.getUsed())){
            //BASE64编码
            LOGGER.info("编码前body======"+body);
            body = Base64.getEncoder().encodeToString(body.getBytes(Constants.GBK));
            LOGGER.info("编码后body======"+body);
        }
        swReq.setBody("<![CDATA["+body+"]]>");
        if(Constants.USED.equals(encrypt.getUsed())){
            body = IscUtil.signData(body);
        }
        swReq.setSign("<![CDATA["+body+"]]>");
        swReq.setVersion(Constants.INTERFACE_VERSION);
        // swReq.setXmlns("http://www.chinatax.gov.cn/spec/");
        //swReq.setXmlnsxsi("http://www.chinatax.gov.cn/spec/");
        swReq.setXmlnsxsi("http://www.w3.org/2001/XMLSchema-instance");
        //swReq.setBody();
        return swReq;
    }

    /**
     * 处理请求返回信息
     * @param swResponse
     * @return
     * @throws Exception
     */
    public static SwResponse dealRespMsg(SwResponse swResponse) throws Exception {
        String req = swResponse.getSwResponseHeader().getTranSeq();
        String s = swResponse.getSwResponseHeader().getRtnCode();
        Compress compress = swResponse.getSwResponseHeader().getSwReqContentControl().getCompress();
        Encrypt encrypt = swResponse.getSwResponseHeader().getSwReqContentControl().getEncrypt();
        Encode encode = swResponse.getSwResponseHeader().getSwReqContentControl().getEncode();

        String respBody = swResponse.getBody();
        String respSign = swResponse.getSign();
        String regex = "<!\\[CDATA\\[(.*)\\]\\]>";
        Pattern pattern = Pattern.compile(regex);
        Matcher mbody = pattern.matcher(respBody);
        while (mbody.find()) {
            respBody = mbody.group(1);
            System.out.println(respBody);
        }
        Matcher msign = pattern.matcher(respSign);
        while (msign.find()) {
            respSign = msign.group(1);
            System.out.println(respSign);
        }

        int errCode= Constants.ErrCode;
        if(Constants.USED.equals(encrypt.getUsed())){
            errCode = IscUtil.verifySign(respBody,respSign);
        }
        if(errCode==Constants.ErrCode){
            if(Constants.USED.equals(encode.getUsed())){
                //BASE64解码
                LOGGER.info("解码前body: "+respBody);
                respBody = new String(Base64.getDecoder().decode(respBody), Constants.GBK);
                LOGGER.info("解码后body: "+respBody);

            }
            if(Constants.USED.equals(compress.getUsed())){
                //解压缩
                respBody = GZIPUtils.uncompress(respBody);
            }
            swResponse.setBody(respBody);
        }
        return swResponse;
    }
    public static String respJsonString(SwResponse swResponse){
        JSONObject respJson = new JSONObject();
        JSONObject msgJson = new JSONObject();
        msgJson.put("tran_id",swResponse.getSwResponseHeader().getTranId());
        msgJson.put("tran_seq",swResponse.getSwResponseHeader().getTranSeq());
        msgJson.put("body",swResponse.getBody());
        respJson.put("Request",msgJson);
        return msgJson.toJSONString();
    }

}
